<?php
class importMotulAction extends CAction {
	public function run(){
		ini_set('memory_limit', '650M');
		set_time_limit(0);
		
		$form=new ImportForm;
		$result = array();

		if(isset($_POST['ImportForm']))
		{
			
			$form->attributes=$_POST['ImportForm'];

			if($form->validate()) {
				# Вот тут начинается импорт
				
				#TyreSizes::model()->updateAll(array('rest'=>0, 'price'=>0));

				$uploaded = Yii::app()->file->set('ImportForm[file]');
				Yii::app()->file->set(Yii::getPathOfAlias('webroot.files.'.$this->controller->id.'.'.$this->controller->action->id))->createDir();
				$newfile = $uploaded->copy(strtolower(Yii::getPathOfAlias('webroot.files.'.$this->controller->id.'.'.$this->controller->action->id)).'/'.$uploaded->basename);

				$newfile->filename = $newfile->filename.'.'.date('YmdHis'); 

				$course = $this->course();
				
				Yii::import('ext.phpexcelreader.EPhpExcelReader');
				$data=new EPhpExcelReader($newfile->realpath, false);
				$sheet = 0;
				$rowcount = $data->rowcount($sheet);
				$result['rowcount'] = $rowcount;
				$result['count'] = 0;
				#$colcount = $data->colcount();
				#$rowcount = 8;
				$r = 1;
				
				Motul::model()->deleteAll();
				
				while($r <= $rowcount) {
					/*
					 * 1. Применяемость (type)
					 * 2. Тип (part_id)
					 * 3. Название (title)
					 * 4. sae (sae)
					 * 5. Стандарты и одобрения (standart)
					 * 6. Описание (description)
					 * 7. Новый артикул (articul)
					 * 8. Ед. Бнк / Бочка (volume)
					 * 9. Шт. в упаковке (in_pack)
					 * 10. Розничная цена (price_out)
					 * 11. Оптовая цена (price_in)
					 */
					
					$motul = new Motul;
					$motul->type = L::r_ruitem('gsmUsage', $data->val($r, 1, $sheet));
					$motul->part_id = L::r_ruitem('gsmType', $data->val($r, 2, $sheet));
					$motul->title = $data->val($r, 3, $sheet);
					$motul->sae = $data->val($r, 4, $sheet);
					$motul->alias = EString::strtolower(EString::sanitize( $motul->title.'_'.$motul->sae ));
					$motul->standart = $data->val($r, 5, $sheet);
					$motul->description = '<p>'.$data->val($r, 6, $sheet).'</p>';
					$motul->articul = (int)$data->val($r, 7, $sheet)?(int)$data->val($r, 7, $sheet):null;
					$motul->volume = (int)$data->val($r, 8, $sheet);
					$motul->in_pack = $data->val($r, 9, $sheet);
					$motul->price_out = ceil(str_replace(',','.',$data->val($r, 10, $sheet))*$course*($form->margin/100+1));
					$motul->price_in = ceil(str_replace(',','.',$data->val($r, 11, $sheet))*$course);

					if(!$motul->save()){
						$result['errors']['oil:'.$data->val($r, 3, $sheet)] = $motul->errors;
					}
					
					$result['count']++;
					$r++;
				}
				
				#$this->redirect(array('view','id'=>$model->id));
			}
		}
		
		$this->controller->render('import',array(
			'model'=>$form,
			'results'=>$result,
		));
		Yii::app()->end();
	}
	
	private function course(){
		$date = date("d/m/Y"); 
		$link = "http://www.cbr.ru/scripts/XML_daily.asp?date_req=$date"; 
		$fd = fopen($link, "r"); 
		$text=""; 
		if (!$fd)
			echo "Запрашиваемая страница не найдена"; 
		else { 
			while (!feof ($fd)) $text .= fgets($fd, 4096); 
		}
		fclose ($fd); 
		
		$pattern = "#<Valute ID=\"([^\"]+)[^>]+>[^>]+>([^<]+)[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>([^<]+)[^>]+>[^>]+>([^<]+)#i"; 
		preg_match_all($pattern, $text, $out, PREG_SET_ORDER); 
		$dollar = ""; 
		$euro = "";
		foreach($out as $cur) { 
			if($cur[2] == 840) $dollar = str_replace(",",".",$cur[4]); 
			if($cur[2] == 978) $euro   = str_replace(",",".",$cur[4]); 
		}
		return $euro; 
	}
}